﻿using System.Collections.Generic;
using IDAL;
using Model;
using NHibernate;

namespace SqlDALLibrary
{
    public class DownloadHistoryDal : IDownloadHistoryDAL
    {
        public void saveDownloadHistory(DownloadHistory downloadHistory)
        {
            NHibernateHelper nh = new NHibernateHelper();
            ISession session = nh.GetSession();
            using (var tx = session.BeginTransaction())
            {
                session.Save(downloadHistory);
                tx.Commit();
            }
            session.Close();
        }

        public IList<DownloadHistory> getDownloadHistory(User user)
        {
            NHibernateHelper nh = new NHibernateHelper();
            ISession session = nh.GetSession();
            IList<DownloadHistory> downloadHistoryList = session
                    .CreateQuery("from DownloadHistory d where d.user=:user")
                    .SetParameter("user", user)
                    .List<DownloadHistory>();
            session.Close();
            return downloadHistoryList;
        }

        public IList<DownloadHistory> getDownloadHistory(Resource resource)
        {
            NHibernateHelper nh = new NHibernateHelper();
            ISession session = nh.GetSession();
            IList<DownloadHistory> downloadHistoryList = session
                    .CreateQuery("from DownloadHistory d where d.resource=:resource")
                    .SetParameter("resource", resource)
                    .List<DownloadHistory>();
            session.Close();
            return downloadHistoryList;
        }

        public DownloadHistory getDownloadHistory(User user, Resource resource)
        {
            NHibernateHelper nh = new NHibernateHelper();
            ISession session = nh.GetSession();
            DownloadHistory downloadHistory = session
                    .CreateQuery("from DownloadHistory d where d.user=:user and d.resource=:resource")
                    .SetParameter("user", user)
                    .SetParameter("resource", resource)
                    .UniqueResult<DownloadHistory>();
            session.Close();
            return downloadHistory;
        }

        public DownloadHistory getDownloadHistory(int downloadHistoryId)
        {
            NHibernateHelper nh = new NHibernateHelper();
            ISession session = nh.GetSession();
            DownloadHistory downloadHistory = session
                    .CreateQuery("from DownloadHistory d where d.id=:id")
                    .SetInt32("id", downloadHistoryId)
                    .UniqueResult<DownloadHistory>();
            session.Close();
            return downloadHistory;
        }

    }
}
